import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {PagesService} from '../pages.service';
import {Setting} from '../../../public/setting/setting';
import {SettingUrl} from '../../../public/setting/setting_url';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public validateForm: FormGroup;//登录的表单
  public app = Setting.APP; //平台信息

  constructor(public fb: FormBuilder, private pagesService: PagesService, public router: Router) {
    this.validateForm = this.fb.group({
      account: [null, [Validators.required]],
      password: [null, [Validators.required]],
    });
    let token = localStorage.getItem(Setting.storage.authorizationToken);
    if (token) this.router.navigate([SettingUrl.ROUTERLINK.basic.home], {replaceUrl: true});//如果有token，跳转到首页
  }

  ngOnInit() {
  }

  /**
   * 登录
   * @param $event
   * @param value
   */

  login = ($event) => {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    me.pagesService.login(me.validateForm.value).then((data: string) => {
      localStorage.setItem(Setting.storage.authorizationToken, data);
      me.router.navigate([SettingUrl.ROUTERLINK.basic.home]);//登陆成功
    });
  };


  /**
   * from表单
   * @param name
   * @returns {AbstractControl}
   */
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

}
